<template>
  <div class="edit_box">
    <el-scrollbar>
      <el-form
        ref="csForm"
        class="csForm"
        :model="pageData.formData"
        :rules="pageData.formRules"
        status-icon
        label-width="120px"
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="机构编号：" prop="fOrgCode">
              <el-input
                v-model="pageData.formData.fOrgCode"
                placeholder="请输入保障机构编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构名称：" prop="fOrgName">
              <el-input
                v-model="pageData.formData.fOrgName"
                placeholder="请输入保障机构名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="注册地址：" prop="fRegAddress">
              <el-input
                v-model="pageData.formData.fRegAddress"
                placeholder="请输入注册地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构分类：" prop="fOrgCategory">
              <el-select
                v-model="pageData.formData.fOrgCategory"
                placeholder="请选择机构分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in pageData.jgtype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内部/外部：" prop="fIsInside">
              <el-select
                v-model="pageData.formData.fIsInside"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in pageData.unit"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资质等级：" prop="fCredential">
              <!-- <el-select
                v-model="pageData.formData.fCredential"
                placeholder="请选择资质等级"
                style="width: 100%"
                @visible-change="selectzbType"
                @change="selectTypeId"
              >
                <el-option
                  v-for="item in pageData.zzIndex"
                  :key="item.fId"
                  :label="item.label"
                  :value="item.fEcName"
                />
              </el-select> -->
              <el-input
                v-model="pageData.formData.fCredential"
                placeholder="请输入资质等级"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人：" prop="fContact">
              <el-input
                v-model="pageData.formData.fContact"
                placeholder="请输入联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话：" prop="fPhone">
              <el-input
                v-model="pageData.formData.fPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="录入人员：">
              <el-input
                v-model="pageData.formData.fCreateUserName"
                autocomplete="off"
                :disabled="!pageData.isAdd || pageData.isAdd"
                placeholder="自动填充"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="录入时间：">
              <el-input
                v-model="pageData.formData.fCreatorTime"
                autocomplete="off"
                :disabled="!pageData.isAdd || pageData.isAdd"
                placeholder="自动填充"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input
                v-model="pageData.formData.fRemark"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 子表 -->
        <el-row>
          <el-button type="primary" @click="onHandleEquipAdd">
            <el-icon><Plus /></el-icon>
            <span>新增</span>
          </el-button>
          <el-table
            height="250"
            border
            style="width: 100%; margin: 10px 0"
            :data="pageData.formData.orgDtls"
          >
            <el-table-column
              type="index"
              width="60"
              align="center"
              label="序号"
            />
            <!-- <el-table-column prop="fSort" label="序号：">
              <template #default="{ row }">
                <el-input
                  v-model="row.fSort"
                  readonly
                  autocomplete="off"
                  placeholder="自动填充"
                >
                </el-input> </template
            ></el-table-column> -->
            <el-table-column prop="fServiceUnitCode" label="服务单位编号">
              <template #default="{ row }">
                <el-input
                  v-model="row.fServiceUnitCode"
                  placeholder="请输入服务单位编号"
                />
              </template>
            </el-table-column>
            <el-table-column prop="fServiceUnitName" label="服务单位名称">
              <template #default="{ row }">
                <el-input
                  v-model="row.fServiceUnitName"
                  placeholder="请输入服务单位名称"
                />
              </template>
            </el-table-column>
            <el-table-column prop="fRemark" label="备注">
              <template #default="{ row }">
                <el-input v-model="row.fRemark" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60">
              <template #default="{ row }">
                <el-icon
                  title="删除"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleEquipDel(row)"
                >
                  <Delete />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row>
      <el-col :span="24" style="text-align: right">
        <el-button @click="onHandleCancel">取消</el-button>
        <el-button type="primary" @click="onHandleSure"> 提交 </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { onMounted, reactive, ref, watch } from "vue";
import { ElLoading, ElMessage,ElMessageBox } from "element-plus";
import { Plus, Delete, ArrowDown } from "@element-plus/icons-vue";
import selectmtrparam from "@/components/select/selectmtrparam.vue";

import {
  add_jg,
  details_jg,
  update_jg,
  delete_jgzb,
} from "@/api/basic/safeguardorganization";

export default {
  components: { Plus, Delete, ArrowDown, selectmtrparam },

  props: {
    modifyObj: { type: Object, required: true },
    isAdd: { type: Boolean, required: true, default: false },
  },
  setup(props, context) {
    onMounted(() => {
      pageData.formData = {
        fAuditUserId: "",
        fAuditorTime: "",
        fBookCode: "",
        fContact: "",
        fCreateUserId: "",
        fCreatorTime: "",
        fCredential: "",
        fId: "",
        fIsInside: "",
        fLastModifyTime: "",
        fLastModifyUserId: "",
        fOrgCode: "",
        fOrgName: "",
        fPhone: "",
        fRegAddress: "",
        fRemark: "",
        fState: 0,
        orgDtls: [],
        fOrgCategory: "",
      };
    });

    // 表单绑定返回的数据
    const csForm = ref();

    let pageData = reactive({
      // 机构类别
      jgtype: [
        {
          value: 50,
          label: "供应商",
        },
        {
          value: 60,
          label: "生产商",
        },
        {
          value: 70,
          label: "维修厂",
        },
      ],
      // 资质等级
      zzIndex: [],
      // 内部/外部
      unit: [
        {
          value: 1,
          label: "内部",
        },
        {
          value: 2,
          label: "外部",
        },
      ],
      formData: {
        orgDtls: [],
      },
      formRules: {
        fOrgCode: [
          { required: true, message: "请输入机构编号", trigger: "blur" },
        ],
        fOrgName: [
          { required: true, message: "请输入机构名称", trigger: "blur" },
        ],
        fRegAddress: [
          { required: true, message: "请输入注册地址", trigger: "blur" },
        ],
        fContact: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        fPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
        fIsInside: [
          { required: true, message: "请选择内外部", trigger: "blur" },
        ],
        fOrgCategory: [
          { required: true, message: "请选择机构分类", trigger: "blur" },
        ],
      },

      isAdd: props.isAdd,
      currentRow: {},
      selectParamVisible: false, //选择装备参数弹窗
    });

    /* 增加子表中参数信息 */
    const onHandleEquipAdd = () => {
      const dtl = {
        fAuditUserId: "",
        fAuditorTime: "",
        fBookCode: "",
        fCreateUserId: "",
        fCreatorTime: "",
        fDtlId: "",
        fId: "",
        fLastModifyTime: "",
        fLastModifyUserId: "",
        fRemark: "",
        fServiceUnitCode: "",
        fServiceUnitName: "",
        fSort: "",
        fState: 0,
      };
      pageData.formData.orgDtls.push(dtl);
    };
    // 删除参数
    const onHandleEquipDel = (row) => {
      const index = pageData.formData.orgDtls.indexOf(row);
      const fId = pageData.formData.orgDtls[0].fId;
      ElMessageBox.confirm("是否确定删除该参数，删除后不可撤销", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delete_jgzb(fId)
            .then((res) => {
              console.log("删除子表参数", res);
              if (index > -1) {
                pageData.formData.orgDtls.splice(index, 1);
              }
            })
            .catch((error) => {
              // ElMessage.error(error.message || "请求出错");
              ElMessage.error("删除失败");
            });
          // if (index > -1) {
          //   pageData.formData.orgDtls.splice(index, 1);
          // }
        })
        .catch(() => {
          // ElMessage.error(error.message || "请求出错");
          ElMessage.error("删除失败");
        });
      // delete_jgzb(fId)
      //   .then((res) => {
      //     console.log("删除子表参数", res);
      //   })
      //   .catch((error) => {
      //     ElMessage.error(error.message || "请求出错");
      //   });
      // if (index > -1) {
      //   pageData.formData.orgDtls.splice(index, 1);
      // }
    };

    const onHandleCancel = () => {
      csForm.value?.resetFields();
      context.emit("cancel");
    };
    // 查询机构详情
    if (!props.isAdd) {
      details_jg(props.modifyObj.fId) //查询装备详情
        .then((res) => {
          pageData.formData = res[0];
          console.log("121212", res);
          pageData.formData.orgDtls = res[0].orgDtlList;
          // console.log("pageData.formData.orgDtls", pageData.formData.orgDtls);
        })
        .catch((error) => {
          console.log(error);
          ElMessage.error(error.message || "请求出错");
        });
    }
    // 提交
    const onHandleSure = () => {
      csForm.value?.validate((valid) => {
        if (valid) {
          const loading = ElLoading.service({
            lock: true,
            background: "rgba(0, 0, 0, 0.7)",
          });
          if (props.isAdd) {
            console.log("新增", pageData.formData);
            pageData.formData.fPhone = parseInt(pageData.formData.fPhone);
            add_jg(pageData.formData)
              .then((res) => {
                console.log("新增", pageData.formData);
                console.log("返回的数据", res);

                // if(res.msg == '服务单位编号或名称不能为空'){
                //   ElMessage.warning('添加失败！服务单位编号或名称不能为空，请重新输入')
                //   loading.close()
                // }else if(res.msg == '机构编号已存在'){
                //   ElMessage.warning('添加失败！机构编号已存在，请重新输入')
                //   loading.close()
                // }else if(res.msg == '机构名称已存在'){
                //   ElMessage.warning('添加失败！机构名称已存在，请重新输入')
                //   loading.close()
                // }
                context.emit("ok", {
                  isAdd: props.isAdd,
                  retObj: pageData.formData,
                });
                loading.close();
                context.emit("ok", {
                  isAdd: props.isAdd,
                  retObj: pageData.formData,
                });
                loading.close();
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          } else {
            pageData.formData.fCreatorTime = new Date(
              pageData.formData.fCreatorTime
            );

            update_jg(pageData.formData)
              .then((res) => {
                console.log("pageData.formData", pageData.formData);
                console.log("装备编辑", res);
                loading.close();
                context.emit("ok", {
                  isAdd: props.isAdd,
                  retObj: pageData.formData,
                });
              })
              .catch((error) => {
                console.log("error", error);
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          }
        } else return false;
      });
    };

    return {
      csForm,
      pageData,
      onHandleEquipAdd,
      onHandleEquipDel,
      onHandleCancel,
      onHandleSure,
    };
  },
};
</script>

<style lang="scss">
.edit_box {
  height: 100%;
  background-color: white;
  .csForm {
    width: calc(100% - 6px);
  }
}
</style>
